<template>
  <el-dialog
    title="新增联系人"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="700px"
  >
    <el-form
      :model="contractForm"
      :rules="contractFormRules"
      ref="contractForm"
      label-width="80px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contacts">
            <el-input
              v-model="contractForm.contacts"
              placeholder="请输入联系人"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="contacts_mobile">
            <el-input
              v-model="contractForm.contacts_mobile"
              placeholder="请输入联系方式"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false" size="small">取消</el-button>
      <el-button
        type="primary"
        @click="dataFormSubmit"
        size="small"
        v-preventReClick
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { addContracts } from '@/api/user'
export default {
  data () {
    const validateMobile = (rule, value, callback) => {
      if (!this.$valid.isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      studentId: '',
      contractForm: {
        contacts: '',
        contacts_mobile: ''
      },
      contractFormRules: {
        contacts_mobile: [
          { required: true, message: '联系方式不能为空', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init (id) {
      this.visible = true
      this.studentId = id
      this.$nextTick(() => {
        this.$refs['contractForm'].resetFields()
      })
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['contractForm'].validate(valid => {
        if (valid) {
          this.submit()
        }
      })
    },
    async submit () {
      let res = await addContracts({
        'nice_student_contacts.student_id': this.studentId,
        'nice_student_contacts.contacts': this.contractForm.contacts,
        'nice_student_contacts.contacts_mobile': this.contractForm
          .contacts_mobile
      })
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.$message({
          message: '新增联系人成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.visible = false
            this.$emit('refreshDataList')
          }
        })
      } else {
        this.$message.error(data.msg)
      }
    }
  }
}
</script>
